<template>
  <div class="user-info-container">
    <div class="user-header">
      <div class="avatar-section">
        <el-avatar :size="100" :src="userInfo.AvatarUrl || defaultAvatar" />
        <div class="user-basic-info">
          <h2>{{ userInfo.Username }}</h2>
          <p class="user-role">
            {{ userInfo.Role === 0 ? "管理员" : "普通用户" }}
          </p>
        </div>
      </div>
      <div class="stats-section">
        <div class="stat-item">
          <el-icon><User /></el-icon>
          <div>
            <p class="stat-value">{{ userInfo.RealName || "未设置" }}</p>
            <p class="stat-label">真实姓名</p>
          </div>
        </div>
        <div class="stat-item">
          <el-icon><Message /></el-icon>
          <div>
            <p class="stat-value">{{ userInfo.Email || "未设置" }}</p>
            <p class="stat-label">邮箱</p>
          </div>
        </div>
        <div class="stat-item">
          <el-icon><Phone /></el-icon>
          <div>
            <p class="stat-value">{{ userInfo.Phone || "未设置" }}</p>
            <p class="stat-label">手机号</p>
          </div>
        </div>
      </div>
    </div>

    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" link @click="isEditing = !isEditing">
            {{ isEditing ? "取消" : "编辑" }}
          </el-button>
        </div>
      </template>

      <el-form
        v-if="isEditing"
        ref="formRef"
        :model="userInfo"
        :rules="rules"
        label-width="100px"
        class="user-info-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="userInfo.Username" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="RealName">
              <el-input v-model="userInfo.RealName" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio-group v-model="userInfo.Gender">
                <el-radio :label="true">男</el-radio>
                <el-radio :label="false">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期">
              <el-date-picker
                v-model="userInfo.Birthday"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="Email">
              <el-input v-model="userInfo.Email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="Phone">
              <el-input v-model="userInfo.Phone" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div v-else class="user-info-display">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">用户名：</span>
              <span class="info-value">{{ userInfo.Username }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">真实姓名：</span>
              <span class="info-value">{{
                userInfo.RealName || "未设置"
              }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">性别：</span>
              <span class="info-value">{{
                userInfo.Gender === true
                  ? "男"
                  : userInfo.Gender === false
                  ? "女"
                  : "未设置"
              }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">出生日期：</span>
              <span class="info-value">{{
                userInfo.Birthday || "未设置"
              }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">邮箱：</span>
              <span class="info-value">{{ userInfo.Email || "未设置" }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">手机号：</span>
              <span class="info-value">{{ userInfo.Phone || "未设置" }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 修改密码 -->
    <el-card class="info-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      <el-form
        ref="pwdFormRef"
        :model="pwdForm"
        :rules="pwdRules"
        label-width="100px"
        class="user-info-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="pwdForm.oldPassword"
                type="password"
                show-password
                placeholder="请输入原密码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="pwdForm.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码（至少6位）"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="pwdForm.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="handleChangePassword"
            >提交</el-button
          >
          <el-button @click="resetPwdForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { User, Message, Phone } from "@element-plus/icons-vue";
import { userApi } from "../../api/userApi.js";
import { useUserStore } from "../../store";

const userStore = useUserStore();
const formRef = ref(null);
const isEditing = ref(false);
const defaultAvatar = ref(
  "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
);

// 用户信息
const userInfo = computed(() => userStore.userInfo);

// 表单验证规则
const rules = {
  RealName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  Email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  Phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await userApi.updateCurrentUser(userInfo.value);
        ElMessage.success("保存成功");
        isEditing.value = false;
        // 更新用户存储中的信息
        userStore.setUserInfo({
          ...userStore.userInfo,
          realName: userInfo.value.RealName,
          email: userInfo.value.Email,
          phone: userInfo.value.Phone,
          gender: userInfo.value.Gender,
          birthday: userInfo.value.Birthday,
        });
      } catch (error) {
        console.error("保存失败:", error);
        ElMessage.error("保存失败");
      }
    }
  });
};

// 重置表单
const handleReset = () => {
  formRef.value.resetFields();
};

// 修改密码表单
const pwdFormRef = ref(null);
const pwdForm = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const validateConfirm = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请确认新密码"));
  }
  if (value !== pwdForm.value.newPassword) {
    return callback(new Error("两次输入的密码不一致"));
  }
  callback();
};

const pwdRules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "新密码至少6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    { validator: validateConfirm, trigger: "blur" },
  ],
};

const handleChangePassword = async () => {
  if (!pwdFormRef.value) return;
  await pwdFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      await userApi.updatePassword({
        oldPassword: pwdForm.value.oldPassword,
        newPassword: pwdForm.value.newPassword,
      });
      ElMessage.success("密码修改成功");
      pwdForm.value.oldPassword = "";
      pwdForm.value.newPassword = "";
      pwdForm.value.confirmPassword = "";
    } catch (error) {
      console.error("修改密码失败:", error);
      ElMessage.error(error?.message || "修改密码失败");
    }
  });
};

const resetPwdForm = () => {
  pwdFormRef.value?.resetFields();
};

onMounted(() => {});
</script>

<style scoped>
.user-info-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.user-header {
  background: linear-gradient(135deg, #667eea 0%, #00f2fe 100%);
  border-radius: 10px;
  padding: 30px;
  margin-bottom: 20px;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.user-basic-info {
  margin-left: 20px;
}

.user-basic-info h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.user-role {
  margin: 0;
  background: rgba(255, 255, 255, 0.2);
  padding: 5px 10px;
  border-radius: 15px;
  display: inline-block;
}

.stats-section {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  margin: 10px;
}

.stat-item .el-icon {
  font-size: 24px;
  margin-right: 10px;
}

.stat-value {
  margin: 0;
  font-weight: bold;
  font-size: 16px;
}

.stat-label {
  margin: 0;
  font-size: 12px;
  opacity: 0.8;
}

.info-card {
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info-form {
  margin-top: 20px;
}

.user-info-display {
  margin-top: 20px;
}

.info-item {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 5px;
  background-color: #f5f7fa;
  transition: all 0.3s;
}

.info-item:hover {
  background-color: #e9eef5;
  transform: translateY(-2px);
}

.info-label {
  font-weight: bold;
  color: #606266;
}

.info-value {
  color: #303133;
}

@media (max-width: 768px) {
  .user-header {
    padding: 20px;
  }

  .avatar-section {
    flex-direction: column;
    text-align: center;
  }

  .user-basic-info {
    margin: 20px 0 0 0;
  }

  .stats-section {
    flex-direction: column;
  }

  .stat-item {
    justify-content: center;
  }
}
</style>
